package org.example.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class IndexUtil {
    private static final List<Integer> indexPool = Collections.synchronizedList(new ArrayList<>());
    private static final int MIN_Index = 1;
    private static final int MAX_Index = 2^16-1;

    static {
        for (int i = MIN_Index; i <= MAX_Index; i++) {
            indexPool.add(i);
        }
    }

    public static int getAvailableIndex() {
        synchronized (indexPool) {
            if (!indexPool.isEmpty()) {
                int index = new Random().nextInt(indexPool.size());
                return indexPool.remove(index);
            }
            throw new RuntimeException("No available index!");
        }
    }

    public static void releaseIndex(int index) {
        synchronized (indexPool) {
            // 防止重复添加
            if (!indexPool.contains(index)) {
                indexPool.add(index);
            }
        }
    }
}
